//校验登录
checkLogin()
//渲染用户名
usernameRander()

//退出登录
logoutLogin()

//渲染数据
async function randerStudent() {
    const res = await axios({
        url: '/students'
    })

    //渲染
    const list = document.querySelector('.list')
    document.querySelector('.total').innerHTML = res.data.length
    list.innerHTML = res.data.map(ele => {
        const { id, name, age, gender, group, hope_salary, salary, province, city, area } = ele
        return `
                <tr>
                      <td>${name}</td>
                      <td>${age}</td>
                      <td>${gender === 0 ? '男' : '女'}</td>
                      <td>第${group}组</td>
                      <td>${hope_salary}</td>
                      <td>${salary}</td>
                      <td>${province + city + area}</td>
                      <td data-id=${id}>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                      </td>
                    </tr>
                `
    }).join('')

}
randerStudent()


const modal = document.querySelector('#modal')
const modalDom = new bootstrap.Modal(modal)
//初始化省市区数据
async function initdata() {
    const btn = document.querySelector('#openModal')
    const provinceDom = document.querySelector('[name=province]')
    const cityDom = document.querySelector('[name=city]')
    const areaDom = document.querySelector('[name=area]')
    //省市区联动
    const province = await axios({
        url: '/api/province'
    })
    const provinceList = province.list

    provinceDom.innerHTML = '<option value="">--省份--</option>' + provinceList.map(ele => {
        return `<option value="${ele}">${ele}</option>`
    }).join('')


    //市区
    provinceDom.addEventListener('change', async () => {
        const city = await axios({
            url: '/api/city',
            params: {
                pname: provinceDom.value
            }
        })
        const cityList = city.list
        cityDom.innerHTML = '<option value="">--城市--</option>' + cityList.map(c => {
            return `<option value="${c}">${c}</option>`
        }).join('')

        document.querySelector('[name=area]').innerHTML = '<option value="">--地区--</option>'

    })

    //地区
    cityDom.addEventListener('change', async () => {
        const area = await axios({
            url: '/api/area',
            params: {
                pname: provinceDom.value,
                cname: cityDom.value
            }
        })
        const areaList = area.list
        areaDom.innerHTML = '<option value="">--地区--</option>' + areaList.map(k => {
            return `<option value="${k}">${k}</option>`
        }).join('')
    })
    btn.addEventListener('click', async e => {
        document.querySelector('.modal-title').innerHTML = '新增学员'
        document.querySelector('#form').reset()
        cityDom.innerHTML = '<option value="">--城市--</option>'
        document.querySelector('[name=area]').innerHTML = '<option value="">--地区--</option>'
        modal.dataset.id = ''

        modalDom.show()


    })
}
initdata()


document.querySelector('#submit').addEventListener('click', e => {
    if (modal.dataset.id) {
        saveEdit()
    } else {
        addStudent()
    }

})


//新增学生
async function addStudent() {
    const form = document.querySelector('#form')
    const data = serialize(form, { hash: true, empty: true })
    data.age = +data.age
    data.gender = +data.gender
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    data.group = +data.group

    try {
        const res = await axios.post('/students', data)
        showToast(res.message)
        randerStudent()
    } catch (error) {
        showToast(error.response.data.message)
    }

    modalDom.hide()
    form.reset()
}

document.querySelector('.list').addEventListener('click', e => {
    const id = e.target.parentNode.parentNode.dataset.id
    if (e.target.classList.contains('bi-trash')) {

        deleteStu(id)
    }

    if (e.target.classList.contains('bi-pen')) {
        updateStu(id)
    }
})

//删除学生
async function deleteStu(id) {
    if (confirm('你确定要删除吗')) {
        const res = await axios.delete(`/students/${id}`)
        showToast('删除成功!')
        randerStudent()
    } else {
        showToast('已取消!')
    }

}

//编辑学生
async function updateStu(id) {
    document.querySelector('.modal-title').innerHTML = '编辑学员'
    const res = await axios.get('/students/' + id)
    const stuData = res.data
    const stuArr = ['name', 'age', 'group', 'hope_salary', 'salary']
    stuArr.forEach(key => {
        document.querySelector(`[name=${key}]`).value = stuData[`${key}`]
    })

    const genders = document.querySelectorAll('[name="gender"]')
    genders[stuData['gender']].checked = true
    document.querySelector('[name="province"]').value = stuData['province']

    //获取市
    const city = await axios({
        url: '/api/city',
        params: {
            pname: stuData['province']
        }
    })
    //渲染市
    document.querySelector('[name="city"]').innerHTML = '<option value="">--城市--</option>' + city.list.map(k => {
        return `<option value="${k}">${k}</option>`
    })
    document.querySelector('[name="city"]').value = stuData['city']

    //获取区
    const area = await axios({
        url: '/api/area',
        params: {
            pname: stuData['province'],
            cname: stuData['city']
        }
    })
    //渲染区
    document.querySelector('[name="area"]').innerHTML = '<option value="">--地区--</option>' + area.list.map(a => {
        return `<option value="${a}">${a}</option>`
    })
    document.querySelector('[name="area"]').value = stuData['area']


    modalDom.show()
    modal.dataset.id = id
}

//点击修改
async function saveEdit() {
    const form = document.querySelector('#form')
    const data = serialize(form, { hash: true, empty: true })
    data.age = +data.age
    data.gender = +data.gender
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    data.group = +data.group

    try {
        const res = await axios.put(`/students/${modal.dataset.id}`, data)
        showToast(res.message)
        randerStudent()
    } catch (error) {
        showToast(error.response.data.message)
    }

    modalDom.hide()

}